"""
用梯度下降的优化方法来快速解决线性回归问题
"""

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

from numpy import *

# 构建数据

points_num = 100
vectors = []

# 正态随即分部函数100个点
# y=0.1*x+0.2 权重（Weight）0.1

for i in range(points_num):
    x1 = np.random.normal(0.0, 0.66)
    y1 = 0.1 * x1 + 0.2 + np.random.normal(0.0, 0.04)
    vectors.append([x1, y1])

x_data = [v[0] for v in vectors]
y_data = [v[1] for v in vectors]

# 图像1：展示所有的100个随机数据点

plt.plot(x_data, y_data, "r*", label="Original data")
plt.title("Linear Regression using Gradient Descent")
plt.legend()
plt.show()

W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b

loss = tf.reduce_mean(tf.square(y - y_data))

# 梯度下降优化器
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

# 创建会话
sess = tf.Session()

init = tf.global_variables_initializer()

sess.run(init)

# 训练步数

for step in range(20):
    # 优化每一步
    sess.run(train)
    # 打印每一步的损失，权重和偏差
    print("Step=%d, Loss=%f, [Weight=%f Bias=%f]" % (step, sess.run(loss), sess.run(W), sess.run(b)))

# 图像2，绘制所有的点并且绘制出最佳你和曲线
plt.plot(x_data, y_data, "r*", label="Original data")
plt.title("Linear Regression using Gradient Descent")
plt.plot(x_data, sess.run(W) * x_data + sess.run(b), label="Fitted line")
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.show()

# 关闭会话
sess.close()

quit()